<template>
  <div class="min-h-screen bg-gradient-to-br from-blue-50 to-purple-50">
    <div class="container mx-auto px-6 py-8">
      <!-- 页面标题 -->
      <div class="text-center mb-8">
        <h1 class="text-3xl font-bold text-gray-900 mb-2">大五人格测评结果</h1>
        <p class="text-gray-600">基于您完成的5个问卷的综合分析报告</p>
      </div>

      <!-- 加载状态 -->
      <div v-if="loading" class="text-center py-12">
        <div
          class="inline-block animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"
        ></div>
        <p class="mt-4 text-gray-600">正在生成综合评估结果...</p>
      </div>

      <!-- 结果内容 -->
      <div v-else-if="personalityData.length > 0" class="space-y-8">
        <!-- 总体评分 -->
        <div class="bg-white rounded-xl shadow-lg p-6">
          <h2
            class="text-xl font-semibold text-gray-900 mb-4 flex items-center"
          >
            <i class="pi pi-chart-line mr-2 text-blue-600"></i>
            总体评分
          </h2>
          <div class="flex items-center justify-center">
            <div class="text-center">
              <div class="text-6xl font-bold text-blue-600 mb-2">
                {{ overallScore }}
              </div>
              <div class="text-gray-600">综合评分</div>
            </div>
          </div>
        </div>

        <!-- 大五人格雷达图 -->
        <div class="bg-white rounded-xl shadow-lg p-6">
          <h2
            class="text-xl font-semibold text-gray-900 mb-4 flex items-center"
          >
            <i class="pi pi-chart-bar mr-2 text-green-600"></i>
            大五人格雷达图
          </h2>
          <div class="flex justify-center">
            <v-chart class="chart" :option="radarOption" />
          </div>
        </div>

        <!-- 各维度详细分析 -->
        <div class="bg-white rounded-xl shadow-lg p-6">
          <h2
            class="text-xl font-semibold text-gray-900 mb-6 flex items-center"
          >
            <i class="pi pi-chart-bar mr-2 text-purple-600"></i>
            人格系数正负分布图
          </h2>
          <div class="mb-4 text-sm text-gray-600 text-center">
            <span class="inline-block bg-blue-50 px-3 py-1 rounded-full mr-3">
              <i class="pi pi-arrow-left text-blue-600 mr-1"></i>
              负值：特质较低
            </span>
            <span class="inline-block bg-gray-100 px-3 py-1 rounded-full mr-3">
              0：中性水平
            </span>
            <span class="inline-block bg-green-50 px-3 py-1 rounded-full">
              <i class="pi pi-arrow-right text-green-600 mr-1"></i>
              正值：特质较高
            </span>
          </div>
          <div class="flex justify-center mb-6">
            <v-chart class="chart-bar" :option="barOption" />
          </div>
        </div>

        <!-- 各维度详细解读 -->
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
          <div
            v-for="(item, index) in personalityData"
            :key="index"
            class="bg-white rounded-xl shadow-lg p-6 hover:shadow-xl transition-shadow duration-300"
          >
            <div class="flex items-center justify-between mb-4">
              <h3 class="text-lg font-semibold text-gray-900 flex items-center">
                <div
                  class="w-4 h-4 rounded-full mr-3"
                  :style="{ backgroundColor: dimensionColors[index] }"
                ></div>
                {{ item.dimension }}
              </h3>
              <div class="flex items-center space-x-2">
                <span
                  class="text-2xl font-bold"
                  :style="{ color: dimensionColors[index] }"
                >
                  {{ item.coefficient.toFixed(2) }}
                </span>
                <span class="text-gray-500 text-sm">系数</span>
              </div>
            </div>

            <!-- 系数显示条 -->
            <div class="mb-4">
              <div class="flex justify-between text-xs text-gray-500 mb-1">
                <span>较低 (< -1)</span>
                <span>中等 (-1 ~ 1)</span>
                <span>较高 (> 1)</span>
              </div>
              <div class="w-full bg-gray-200 rounded-full h-2">
                <div
                  class="h-2 rounded-full transition-all duration-500"
                  :style="{
                    width:
                      convertCoeffToDisplayValue(item.coefficient) * 100 + '%',
                    backgroundColor: dimensionColors[index],
                  }"
                ></div>
              </div>
            </div>

            <!-- 水平标签 -->
            <div class="text-center mb-4">
              <span
                class="inline-block px-3 py-1 rounded-full text-sm font-medium"
                :style="{
                  backgroundColor: dimensionColors[index] + '20',
                  color: dimensionColors[index],
                }"
              >
                {{ item.level }}
              </span>
            </div>

            <!-- 详细描述 -->
            <div class="text-sm text-gray-600 leading-relaxed">
              {{ item.result }}
            </div>
          </div>
        </div>

        <!-- 综合建议 -->
        <div
          class="bg-gradient-to-r from-blue-50 to-purple-50 rounded-xl shadow-lg p-6"
        >
          <h2
            class="text-xl font-semibold text-gray-900 mb-4 flex items-center"
          >
            <i class="pi pi-lightbulb mr-2 text-yellow-600"></i>
            个性化建议
          </h2>
          <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div
              v-for="(recommendation, index) in getRecommendations()"
              :key="index"
              class="bg-white rounded-lg p-4 border-l-4 border-blue-500"
            >
              <h4 class="font-medium text-gray-900 mb-2">
                {{ recommendation.title }}
              </h4>
              <p class="text-sm text-gray-600">
                {{ recommendation.description }}
              </p>
            </div>
          </div>
        </div>

        <!-- 操作按钮 -->
        <div class="flex justify-center space-x-4">
          <Button
            label="下载详细报告"
            icon="pi pi-file-pdf"
            @click="downloadReport"
            class="bg-blue-600 hover:bg-blue-700 border-blue-600 hover:border-blue-700 transition-colors duration-300"
          />
          <Button
            label="重新测试"
            icon="pi pi-refresh"
            severity="secondary"
            @click="restartTest"
            class="transition-colors duration-300"
          />
          <Button
            label="返回首页"
            icon="pi pi-home"
            severity="info"
            @click="goHome"
            class="transition-colors duration-300"
          />
        </div>
      </div>

      <!-- 错误状态 -->
      <div v-else-if="error" class="text-center py-12">
        <div class="text-red-500 text-6xl mb-4">⚠️</div>
        <h3 class="text-xl font-semibold text-gray-900 mb-2">获取结果失败</h3>
        <p class="text-gray-600 mb-4">{{ error }}</p>
        <Button
          label="重试"
          icon="pi pi-refresh"
          @click="loadFinalResult"
          class="bg-blue-600 hover:bg-blue-700 border-blue-600 hover:border-blue-700 transition-colors duration-300"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from "vue";
import { useRoute, useRouter } from "vue-router";
import { userAnswerApi } from "@/api/userAnswer.js";
import { useQuestionnaireGroup } from "@/composables/useQuestionnaireGroup.js";
import { use } from "echarts/core";
import { CanvasRenderer } from "echarts/renderers";
import { RadarChart, BarChart } from "echarts/charts";
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
} from "echarts/components";
import VChart from "vue-echarts";

// 注册 ECharts 组件
use([
  CanvasRenderer,
  RadarChart,
  BarChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
]);

// PrimeVue 组件
import Button from "primevue/button";

const route = useRoute();
const router = useRouter();

// 响应式数据
const loading = ref(true);
const error = ref(null);
const personalityData = ref([]);

// 使用问卷组管理
const { clearAll } = useQuestionnaireGroup();

// 获取问卷组ID
const userAnswerGroupId = route.params.groupId;
const userInfo = JSON.parse(sessionStorage.getItem("pmp-userInfo")) || {};
const userId = userInfo.userId || "";
const userName = userInfo.realName || userInfo.username  || "";

// 大五人格维度名称和颜色
const dimensionNames = ["外倾性", "宜人性", "尽责性", "神经质", "开放性"];
const dimensionColors = ["#3B82F6", "#10B981", "#F59E0B", "#EF4444", "#8B5CF6"];

// 将系数转换为 0-1 的显示值用于图表
const convertCoeffToDisplayValue = (coeff) => {
  // 将系数范围从大约 -2 到 2 映射到 0-1
  // 使用sigmoid函数进行平滑映射
  return 1 / (1 + Math.exp(-coeff));
};

// 计算总体评分 - 基于系数的绝对值和平衡性
const overallScore = computed(() => {
  if (personalityData.value.length === 0) return "N/A";

  // 计算方法：基于人格特质的平衡性和整体健康度
  const coefficients = personalityData.value.map((item) => item.coefficient);

  // 1. 计算平衡性得分（系数越接近0越平衡，最高40分）
  const balanceScore =
    coefficients.reduce((sum, coeff) => {
      const distance = Math.abs(coeff);
      return sum + Math.max(0, 40 - distance * 20); // 距离0越远扣分越多
    }, 0) / coefficients.length;

  // 2. 避免极端值的惩罚（最高30分）
  const extremeScore =
    coefficients.reduce((sum, coeff) => {
      const penalty = Math.abs(coeff) > 2 ? 20 : 0; // 极端值（>2或<-2）扣分
      return sum + (30 - penalty);
    }, 0) / coefficients.length;

  // 3. 适应性得分（中等范围内的系数更有利，最高30分）
  const adaptabilityScore =
    coefficients.reduce((sum, coeff) => {
      if (Math.abs(coeff) <= 1) return sum + 30; // 中等范围满分
      if (Math.abs(coeff) <= 1.5) return sum + 20; // 稍高/稍低
      return sum + 10; // 较极端
    }, 0) / coefficients.length;

  const totalScore = Math.round(
    balanceScore + extremeScore + adaptabilityScore
  );
  return Math.min(100, Math.max(0, totalScore)); // 确保在0-100范围内
});

// 雷达图配置
const radarOption = computed(() => ({
  tooltip: {
    trigger: "item",
    formatter: function (params) {
      const index = params.dataIndex;
      const data = personalityData.value[index];
      if (data) {
        return `${data.dimension}<br/>系数: ${data.coefficient.toFixed(
          2
        )}<br/>水平: ${data.level}`;
      }
      return "";
    },
  },
  radar: {
    indicator: dimensionNames.map((name, index) => ({
      name: name,
      max: 1,
    })),
    radius: 120,
    axisName: {
      fontSize: 14,
      color: "#333",
      fontWeight: "bold",
    },
    axisLabel: {
      show: false, // 隐藏轴标签，避免混乱
    },
    splitArea: {
      areaStyle: {
        color: ["rgba(59, 130, 246, 0.1)", "rgba(59, 130, 246, 0.05)"],
      },
    },
    axisLine: {
      lineStyle: {
        color: "rgba(59, 130, 246, 0.2)",
      },
    },
    splitLine: {
      lineStyle: {
        color: "rgba(59, 130, 246, 0.2)",
      },
    },
  },
  series: [
    {
      type: "radar",
      data: [
        {
          value: personalityData.value.map((item) =>
            convertCoeffToDisplayValue(item.coefficient)
          ),
          name: "您的人格特质",
          symbol: "circle",
          symbolSize: 8,
          lineStyle: {
            color: "#3B82F6",
            width: 3,
          },
          areaStyle: {
            color: "rgba(59, 130, 246, 0.2)",
          },
          itemStyle: {
            color: "#3B82F6",
          },
        },
      ],
    },
  ],
}));

// 双向柱状图配置 - 支持正负值
const barOption = computed(() => {
  // 计算合适的Y轴范围
  const coefficients = personalityData.value.map((item) => item.coefficient);
  const maxAbs = Math.max(...coefficients.map((c) => Math.abs(c)));
  const yAxisMax = Math.ceil(maxAbs * 1.2 * 10) / 10; // 留一些边距，保留一位小数

  return {
    title: {
      text: "人格维度系数分布",
      left: "center",
      textStyle: {
        fontSize: 16,
        color: "#333",
        fontWeight: "bold",
      },
    },
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow",
      },
      formatter: function (params) {
        const data = params[0];
        const index = data.dataIndex;
        const personalityItem = personalityData.value[index];
        if (personalityItem) {
          return `${
            personalityItem.dimension
          }<br/>系数: ${personalityItem.coefficient.toFixed(2)}<br/>水平: ${
            personalityItem.level
          }`;
        }
        return "";
      },
    },
    grid: {
      left: "15%",
      right: "10%",
      bottom: "15%",
      top: "15%",
      containLabel: true,
    },
    xAxis: {
      type: "value",
      min: -yAxisMax,
      max: yAxisMax,
      axisLabel: {
        color: "#666",
        fontSize: 12,
        formatter: function (value) {
          return value.toFixed(1);
        },
      },
      axisLine: {
        lineStyle: {
          color: "#E5E7EB",
        },
      },
      splitLine: {
        lineStyle: {
          color: "#F3F4F6",
        },
      },
      // 添加零刻度线
      splitNumber: 8,
    },
    yAxis: {
      type: "category",
      data: dimensionNames,
      axisLabel: {
        color: "#333",
        fontSize: 12,
        fontWeight: "bold",
      },
      axisLine: {
        lineStyle: {
          color: "#E5E7EB",
        },
      },
      axisTick: {
        show: false,
      },
    },
    series: [
      {
        type: "bar",
        data: personalityData.value.map((item, index) => ({
          value: item.coefficient,
          itemStyle: {
            color:
              item.coefficient >= 0
                ? dimensionColors[index]
                : dimensionColors[index] + "80", // 负值稍微透明
          },
        })),
        barWidth: "50%",
        itemStyle: {
          borderRadius: 2,
        },
        // 添加数值标签
        label: {
          show: true,
          position: "inside",
          formatter: function (params) {
            return params.value.toFixed(2);
          },
          color: "#ffffff",
          fontSize: 12,
          fontWeight: "bold",
        },
      },
    ],
  };
});

// 下载文件工具函数
const downloadBlobFile = (data, fileName) => {
  const blob = new Blob([data]);
  const url = URL.createObjectURL(blob);
  const link = document.createElement("a");
  link.href = url;
  link.download = fileName;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  URL.revokeObjectURL(url);
};

// 根据系数获取水平标签
const getLevelLabel = (coefficient) => {
  if (coefficient < -1) return "较低";
  if (coefficient <= 1) return "中等";
  return "较高";
};

// 生成个性化建议
const getRecommendations = () => {
  const recommendations = [];

  personalityData.value.forEach((item, index) => {
    const coeff = item.coefficient;
    const dimension = dimensionNames[index];

    if (dimension === "外倾性") {
      if (coeff < -1) {
        recommendations.push({
          title: "提升社交自信",
          description:
            "逐步拓展舒适区，每周参与一次轻度社交活动，练习主动问候或分享观点。",
        });
      } else if (coeff > 1) {
        recommendations.push({
          title: "平衡独处时间",
          description: "适度保留独处时间，进行深度思考，避免过度依赖外部刺激。",
        });
      }
    }

    if (dimension === "宜人性") {
      if (coeff < -1) {
        recommendations.push({
          title: "增强换位思考",
          description:
            "练习在表达反对前先肯定对方观点，学习建设性冲突管理技巧。",
        });
      } else if (coeff > 1) {
        recommendations.push({
          title: "设立心理边界",
          description: '学习温和而坚定地说"不"，在帮助他人前先评估自身资源。',
        });
      }
    }

    if (dimension === "尽责性") {
      if (coeff < -1) {
        recommendations.push({
          title: "建立基本秩序",
          description: "从小目标开始，使用待办清单、设定每日3件优先任务。",
        });
      } else if (coeff > 1) {
        recommendations.push({
          title: "学会适度放松",
          description:
            '设定"完成标准"而非"完美标准"，定期放松计划，培养灵活性。',
        });
      }
    }

    if (dimension === "神经质") {
      if (coeff < -1) {
        recommendations.push({
          title: "丰富情感表达",
          description: "适度表达情绪，避免压抑感受，关注情绪表达的丰富性。",
        });
      } else if (coeff > 1) {
        recommendations.push({
          title: "情绪调节训练",
          description: "学习认知重构、正念冥想等技巧，建立规律作息与支持系统。",
        });
      }
    }

    if (dimension === "开放性") {
      if (coeff < -1) {
        recommendations.push({
          title: "拓展认知边界",
          description: "每周尝试一项微小新体验，保持对新信息的好奇心。",
        });
      } else if (coeff > 1) {
        recommendations.push({
          title: "增强执行力",
          description: '在发散思维后增加"收敛阶段"，将创意转化为可执行的成果。',
        });
      }
    }
  });

  // 如果没有特殊建议，添加通用建议
  if (recommendations.length === 0) {
    recommendations.push(
      {
        title: "保持平衡发展",
        description: "您的人格特质较为均衡，建议继续保持现有的优势特质。",
      },
      {
        title: "持续自我提升",
        description: "定期进行自我反思，在不同情境中灵活调整行为方式。",
      }
    );
  }

  return recommendations.slice(0, 4); // 最多显示4个建议
};

// 处理原始数据
const processPersonalityData = (rawData) => {
  return rawData.map((item, index) => ({
    dimension: dimensionNames[index],
    coefficient: item.reNum, // 这是系数，不是得分
    level: getLevelLabel(item.reNum), // 根据系数计算水平
    result: item.result,
    userAnswerId: item.userAnswerId,
  }));
};

// 加载最终结果 - 模拟使用用户提供的数据
const loadFinalResult = async () => {
  loading.value = true;
  error.value = null;

  // 模拟API调用，实际项目中应该调用真实API
  const res = await userAnswerApi.getMultiQuestionnaireEvaluationResult(
    userAnswerGroupId
  );
  if (res.success) {
    personalityData.value = processPersonalityData(res.data);
  }
  loading.value = false;
};

// 下载报告
const downloadReport = async () => {
  try {
    const res = await userAnswerApi.downLoadWordBatch(
      userAnswerGroupId,
      userId
    );
    if (res) {
      downloadBlobFile(res.data, `${userName}的大五人格测试报告.docx`);
    } else {
      error.value = "下载报告失败";
    }
  } catch (err) {
    error.value = "下载报告失败，请重试";
    console.error("Error downloading report:", err);
  }
};

// 重新开始测试
const restartTest = () => {
  clearAll();
  router.push("/five/test");
};

// 返回首页
const goHome = () => {
  router.push("/five");
};

// 组件挂载时加载结果
onMounted(() => {
  loadFinalResult();
});
</script>

<style scoped>
/* 图表容器样式 */
.chart {
  width: 100%;
  height: 320px;
}

.chart-bar {
  width: 100%;
  height: 280px;
}

/* 美化滚动条 */
::-webkit-scrollbar {
  width: 6px;
}

::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .chart {
    height: 260px;
  }

  .chart-bar {
    height: 240px;
  }
}

/* 动画效果 */
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.space-y-8 > * {
  animation: fadeInUp 0.6s ease-out;
  animation-fill-mode: both;
}

.space-y-8 > *:nth-child(1) {
  animation-delay: 0.1s;
}
.space-y-8 > *:nth-child(2) {
  animation-delay: 0.2s;
}
.space-y-8 > *:nth-child(3) {
  animation-delay: 0.3s;
}
.space-y-8 > *:nth-child(4) {
  animation-delay: 0.4s;
}
.space-y-8 > *:nth-child(5) {
  animation-delay: 0.5s;
}
.space-y-8 > *:nth-child(6) {
  animation-delay: 0.6s;
}

/* 卡片悬停效果 */
.hover\:shadow-xl:hover {
  transform: translateY(-2px);
  transition: all 0.3s ease;
}

/* 进度条动画 */
.h-2.rounded-full {
  transition: width 1s ease-in-out;
}
</style>
